#!/usr/bin/env node

// check-all-imports.js - 全面检查所有解构导入是否正确

console.log('🔍 检查所有模块导入语法...\n');

const fs = require('fs');
const path = require('path');

// 递归读取所有JS文件
function getAllJsFiles(dir, fileList = []) {
    const files = fs.readdirSync(dir);

    files.forEach(file => {
        const filePath = path.join(dir, file);
        const stat = fs.statSync(filePath);

        if (stat.isDirectory() && !file.includes('node_modules') && !file.startsWith('.')) {
            getAllJsFiles(filePath, fileList);
        } else if (file.endsWith('.js')) {
            fileList.push(filePath);
        }
    });

    return fileList;
}

// 检查文件中的解构导入
function checkDestructuringImports(filePath) {
    try {
        const content = fs.readFileSync(filePath, 'utf8');
        const lines = content.split('\n');

        const issues = [];
        const correctImports = [];

        lines.forEach((line, index) => {
            // 查找解构导入模式
            const destructuringMatch = line.match(/const\s*\{\s*(\w+)\s*\}\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/);

            if (destructuringMatch) {
                const [, importName, modulePath] = destructuringMatch;
                const fullModulePath = path.resolve(path.dirname(filePath), modulePath);

                // 尝试直接加载模块（Node.js会自动解析路径）
                try {
                    const moduleExports = require(modulePath);

                    // 检查导出类型
                    if (typeof moduleExports === 'function' || (typeof moduleExports === 'object' && moduleExports.constructor && moduleExports.constructor.name && moduleExports.constructor.name !== 'Object')) {
                        // 如果导出的是函数或类（非普通对象），则解构导入可能是错误的
                        if (!moduleExports[importName] && moduleExports.name !== importName) {
                            // 检查是否是默认导出的函数/类
                            if (moduleExports.name && moduleExports.name !== 'Object') {
                                issues.push({
                                    file: filePath,
                                    line: index + 1,
                                    import: line.trim(),
                                    error: `可能错误的解构导入：模块导出的是单个${moduleExports.name}类/函数，应该使用直接导入`,
                                    suggestion: `const ${moduleExports.name} = require('${modulePath}')`
                                });
                            }
                        }
                    } else if (typeof moduleExports === 'object' && moduleExports !== null && !Array.isArray(moduleExports)) {
                        // 如果是普通对象，检查是否有对应的属性
                        if (!moduleExports[importName]) {
                            // 检查是否有驼峰命名版本
                            const camelCaseName = importName.charAt(0).toLowerCase() + importName.slice(1);
                            if (moduleExports[camelCaseName]) {
                                issues.push({
                                    file: filePath,
                                    line: index + 1,
                                    import: line.trim(),
                                    error: `属性名大小写不匹配：应该是${camelCaseName}`,
                                    suggestion: `const { ${camelCaseName} } = require('${modulePath}')`
                                });
                            } else {
                                issues.push({
                                    file: filePath,
                                    line: index + 1,
                                    import: line.trim(),
                                    error: `模块中没有导出${importName}属性`,
                                    availableProps: Object.keys(moduleExports).slice(0, 5)
                                });
                            }
                        }
                    }
                } catch (error) {
                    issues.push({
                        file: filePath,
                        line: index + 1,
                        import: line.trim(),
                        error: `模块加载失败: ${error.message}`
                    });
                }
            }
        });

        return { issues, correctImports };

    } catch (error) {
        return {
            issues: [{
                file: filePath,
                line: 0,
                import: '',
                error: `文件读取失败: ${error.message}`
            }],
            correctImports: []
        };
    }
}

// 主检查逻辑
function main() {
    const jsFiles = getAllJsFiles('.');

    console.log(`📁 找到 ${jsFiles.length} 个JavaScript 文件\n`);

    let totalIssues = 0;
    const allIssues = [];

    jsFiles.forEach(file => {
        const { issues, correctImports } = checkDestructuringImports(file);

        if (issues.length > 0) {
            totalIssues += issues.length;
            allIssues.push(...issues);

            console.log(`❌ ${file}:`);
            issues.forEach(issue => {
                console.log(`   第${issue.line}行: ${issue.import}`);
                console.log(`   错误: ${issue.error}`);
                if (issue.suggestion) {
                    console.log(`   建议: ${issue.suggestion}`);
                }
                if (issue.availableProps) {
                    console.log(`   可用属性: [${issue.availableProps.join(', ')}...]`);
                }
                console.log('');
            });
        }
    });

    // 特别检查已知的可能问题模块
    const knownModules = [
        { path: './web-config-server.js', expectedType: 'class', expectedName: 'WebConfigServer' },
        { path: './config-manager.js', expectedType: 'class', expectedName: 'ConfigManager' },
        { path: './lib/config/json-config-manager.js', expectedType: 'class', expectedName: 'JsonConfigManager' },
        { path: './analyze.js', expectedType: 'object' }
    ];

    console.log('🎯 检查已知关键模块的导出:\n');
    knownModules.forEach(({ path, expectedType, expectedName }) => {
        try {
            const moduleExports = require(path);
            console.log(`✅ ${path}:`);
            console.log(`   类型: ${typeof moduleExports}`);
            if (typeof moduleExports === 'function' || (typeof moduleExports === 'object' && moduleExports.name)) {
                console.log(`   构造函数/类名: ${moduleExports.name || 'N/A'}`);
            }
            if (typeof moduleExports === 'object' && Object.keys(moduleExports).length > 0) {
                console.log(`   导出属性: [${Object.keys(moduleExports).slice(0, 5).join(', ')}...]`);
            }
            console.log('');
        } catch (error) {
            console.log(`❌ ${path}:`);
            console.log(`   错误: ${error.message}\n`);
        }
    });

    // 总结报告
    console.log('📊 检查结果总结:');
    console.log(`   - 检查文件数: ${jsFiles.length}`);
    console.log(`   - 发现问题数: ${totalIssues}`);

    if (totalIssues === 0) {
        console.log('\n✅ 所有模块导入语法都正确！');
    } else {
        console.log(`\n⚠️  发现 ${totalIssues} 个潜在的导入问题，请查看上面的详细信息`);

        // 按错误类型分类
        const errorTypes = {};
        allIssues.forEach(issue => {
            const type = issue.error.split(':')[0];
            errorTypes[type] = (errorTypes[type] || 0) + 1;
        });

        console.log('\n📈 错误类型统计:');
        Object.entries(errorTypes).forEach(([type, count]) => {
            console.log(`   ${type}: ${count}个`);
        });
    }

    // 检查是否有类似WebConfigServer的构造函数导入错误
    const webConfigIssues = allIssues.filter(issue =>
        issue.error.includes('单个') &&
        (issue.error.includes('类') || issue.error.includes('函数'))
    );

    if (webConfigIssues.length > 0) {
        console.log('\n🚨 发现类似WebConfigServer的构造函数导入错误！');
        console.log('   这些错误会导致 "XXX is not a constructor" 错误');
        console.log('   请使用直接导入而不是解构导入');
    }

    return totalIssues === 0 ? 0 : 1;
}

// 运行检查
const exitCode = main();
process.exit(exitCode);